<?php
    namespace app\admin\controller;

    // 指定允许其他域名访问
    
    use app\admin\controller\Base;
    use think\captcha\Captcha;
    use think\Config;
    use app\admin\model\Admin as adminModel;
    use think\Session;
    use think\Request;


    class Admin extends  Base
    {
        // 登录验证
        public function index(Request $request)
        {
            // 判断请求类型
            if ($request->isPost()){
                //  验证码验证开始
                $validate = validate('UserValidate');
                // return $request->param();
                $check = $request->only(['captcha']);
                if (!$validate->check($check)){
                    $res = ['status'=>0,'message'=>$validate->getError()];
                    return $res;
                }
                //  验证码验证结束
                
                // 获取参数
                    $username = $request->param('username','trim');
                    $password = $request->param('password','trim');
                // 与数据库信息比对
                    $admin = new adminModel;
                    $res = $admin->checkLogin($username,$password);
                    if ($res['status'] == 0){
                        return $res;
                    }

                    Session::set('username',$username);
                    return $res;

            }elseif ($request->isGet()){
                $res = [
                    'status'=>4,
                    'message'=>'请登录！'
                ];
                return $res;
            }
        }
        // 获取验证码
        public function captcha()
        {
            $config = Config::get('captcha');
            $captcha = new Captcha($config);
            return $captcha->entry();
        }
        // 获取token
        public function getToken()
        {
            $token = $this->request->token('__token__','sha1');
            return ['__token__'=>$token];
        }
        
        // 用户退出登录
        public function logout()
        {
            Session::delete('username');
            $res = [
                'status'=>1,
                'message'=>'已退出登录！'
            ];
            return $res;
        }
        
        // miss路由方法
        public function miss(){
            $res = [
                'status'=>3,
                'message'=>'找不到该页面！'
            ];
            return $res;
        }
        
        public function test(){
            return '已登录';
        }
    }
